<?php

namespace app\admin\model\shop\market\coupon;

use app\admin\model\shop\user\User;
use think\Model;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

/**
 * Receive
 */
class Receive extends Model
{
    use SoftDelete;

    protected $defaultSoftDelete = 0;

    // 表名
    protected $name = 'shop_user_coupon';

    public function coupon(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id', 'id');
    }

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $type = [
        'start_time' => 'timestamp:Y-m-d H:i:s',
        'end_time'   => 'timestamp:Y-m-d H:i:s',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function getRangeGoodsIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setRangeGoodsIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }
}